import { TextToSpeechEngine } from './defined/ttsengine';
import { PluginInterface } from './defined/plugins';
import { Logger } from '../logger';
import { TestResult, TestSuiteResult, PluginTestFramework } from './test-framework';

/**
 * TTS引擎测试扩展
 */
export class TTSTestFramework extends PluginTestFramework {
  /**
   * 测试TTS引擎插件
   */
  static async testTTSEngine(
    plugin: PluginInterface,
    instance: TextToSpeechEngine,
  ): Promise<TestSuiteResult> {
    const results: TestResult[] = [];
    const startTime = Date.now();

    // 测试获取语音列表
    const voiceListResult = await this.runTest(
      'getVoiceList',
      async () => {
        const voices = await instance.getVoiceList();
        if (!Array.isArray(voices)) {
          throw new Error('getVoiceList should return an array');
        }
        if (voices.length === 0) {
          throw new Error('No voices available');
        }
        
        // 验证语音对象格式
        for (const voice of voices) {
          if (!voice.name || !voice.value) {
            throw new Error('Invalid voice object format');
          }
        }
        
        return voices;
      },
    );
    results.push(voiceListResult);

    // 测试文本转语音（简单测试）
    const transformResult = await this.runTest(
      'transform',
      async () => {
        const testTexts = ['测试文本'];
        const abortController = new AbortController();
        
        const chunks: any[] = [];
        let ended = false;
        
        const promise = instance.transform(
          testTexts,
          {
            signal: abortController.signal,
            rate: 0.5,
            volume: 1.0,
          },
          (chunk, index) => {
            chunks.push({ chunk, index });
          },
          () => {
            ended = true;
          },
        );
        
        // 设置超时
        setTimeout(() => {
          abortController.abort();
        }, 5000);
        
        try {
          await promise;
        } catch (error) {
          if (abortController.signal.aborted) {
            // 超时是正常的，说明transform方法在工作
            return { chunks: chunks.length, ended };
          }
          throw error;
        }
        
        return { chunks: chunks.length, ended };
      },
    );
    results.push(transformResult);

    return this.createTestSuiteResult(plugin, results, startTime);
  }

  /**
   * 运行完整的插件测试
   */
  static async runPluginTests(
    plugin: PluginInterface,
    instance: any,
    testConfig?: any,
  ): Promise<TestSuiteResult> {
    switch (plugin.TYPE) {
    case 0: // PluginType.BOOK_SOURCE
      return this.testBookSource(plugin, instance, testConfig);
    case 1: // PluginType.BOOK_STORE
      return this.testBookStore(plugin, instance);
    case 2: // PluginType.TTS_ENGINE
      return this.testTTSEngine(plugin, instance);
    default:
      throw new Error(`Unknown plugin type: ${plugin.TYPE}`);
    }
  }
}